<?php

#require_once 'Zend/Log.php';
require_once 'Zend/Db/Table.php';
require_once 'Zend/Registry.php';
require_once '../RestParser.php';

/**
 * Base class for parsing out a REST rest request.
 */
class PubSubRestParser extends RestParser {

	private $db = null;
	private $robots;
	
    /**
     * Associative array of valid REST operations.
     */
    protected $VALID_REST_ACTIONS = array(
        'subscribe', #Long polling implementation that supports listening for 
        'publish', #Objects support publishing messages to them.
        'unpublish', 
    );
    
    public function __construct($args){
    	parent::__construct($args);
    	$this->db = Zend_Db::factory('Pdo_Pgsql', array('dbname' 	=> 'buster',
    								'host' 		=> 'localhost',
    								'username' 		=> 'buster',
    								'password' 	=> '012345'));
    	Zend_Db_Table::setDefaultAdapter($this->db);
    	$this->robots = new Zend_Db_Table('robot');
    }

    /**
     * Returns an array of the valid REST actions.
     * @return array Valid REST actions.
     */
    public function getValidRestActions() {
        return $this->VALID_REST_ACTIONS;
    }
    
    public function handleAction($action, $restParms){
    	switch(strtolower($action)){
    		case 'publish':
    			$row = $this->publish($restParms);
    			break;
    		case 'unpublish':
    			$row = $this->unpublish($restParms);
    			break;
    		case 'list':
    			//$this->logout();
    			break;
    	}
    	foreach($row as $key => $val){
    		$res[$key] = $val;
    	} 	
    	return $res;
    }
    
    private function publish($restParms){
    	$row = $this->robots->fetchRow("public_ip = '".$_SERVER['REMOTE_ADDR']."' AND public_port = '" . $_SERVER['REMOTE_PORT']. "'");
    	if (!$row){
	    	$row = $this->robots->createRow();
    		$row->userid = $_SESSION['identity'];
    		$row->public_ip = $_SERVER['REMOTE_ADDR'];
    		$row->public_port = $_SERVER['REMOTE_PORT'];
    		$row->private_ip = $restParms['ip'];
    		$row->private_port = $restParms['port'];
    		$row->deviceid = uuid_create(); #new uuid(); #$restParms['deviceid'];
    		$row->save();
    	}   
    	return $row;
    }
    
    private function unpublish($restParms){
    	$row = $this->robots->fetchRow("deviceid = '".$restParms['deviceid']."'");
    	if ($row){
	    	$row->delete();
    	} 
    	return $row;   	
    }
    
}

?>
